package com.cartgo.controller
{
	import com.adobe.crypto.MD5;
	import com.cartgo.events.authentication.AuthenticationEvent;
	import com.cartgo.manager.UserManager;
	import com.cartgo.pmodel.main.MainViewPModel;
	import com.cartgo.services.ICoreDelegates;
	import com.cartgo.vo.errors.VOSqlError;
	import com.cartgo.vo.users.VOUser;
	import com.cartgo.vo.users.VOUserSession;
	
	import flash.events.IEventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import org.swizframework.utils.services.ServiceHelper;

	public class AuthenticationCtrl extends BaseController
	{
		[Inject]
		public var sh:ServiceHelper;
		
		[Inject]
		public var delegate:ICoreDelegates;
		
		[Inject]
		public var model:MainViewPModel;
		
		[Bindable]
		public var userManager:UserManager = UserManager.getInstance();
		
		[Dispatcher]
		public var dispatcher:IEventDispatcher;
		
		public function AuthenticationCtrl()
		{
		}
		
		public function login():void {
			model.user.userPassword = MD5.hash(model.password);
			sh.executeServiceCall(delegate.login(model.user), onLoginResult);
		}
		
		private function onLoginResult(evt:ResultEvent):void
		{
			if(!checkRemoteError(evt)){	
				var userSession:VOUserSession = evt.result as VOUserSession;
				userManager.userSession = userSession;
				var authEvent:AuthenticationEvent = new AuthenticationEvent(AuthenticationEvent.LOGIN_SUCCESS);
				authEvent.userSession = userSession;
				dispatcher.dispatchEvent(authEvent);
			}
		}
		
		public function logout():void {
			sh.executeServiceCall(delegate.signout(userManager.userSession.userId), onLogoutResult);
		}
		
		private function onLogoutResult(evt:ResultEvent):void {
			if(!checkRemoteError(evt)){
				userManager.userSession = null;
				var authEvent:AuthenticationEvent = new AuthenticationEvent(AuthenticationEvent.LOGOUT);
				authEvent.userSession = null;
				dispatcher.dispatchEvent(authEvent);
			}
		}
	}
}